//
//  SISSNetworkingManager.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/21.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSNetworkingManager.h"

#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVMediaFormat.h>
#import <AVFoundation/AVAssetExportSession.h>

@interface SISSNetworkingManager ()

@property (nonatomic,strong) AFJSONRequestSerializer *JSONRequestSerializer;
@property (nonatomic,strong) AFHTTPRequestSerializer *HTTPRequestSerializer;

@end
@implementation SISSNetworkingManager


/**
 *  单例
 *
 *  网络请求类的实例
 */
static SISSNetworkingManager * instance = nil;
+ (instancetype)sharedManager {
    
    static dispatch_once_t onceToken;
    _dispatch_once(&onceToken, ^{
        
        if (instance == nil) {
            
            instance = [[self alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
            //            instance = [[SISSNetworkingManager alloc] init];
            // 设置超时时间
            //            self.requestSerializer.timeoutInterval = 3;
            // 设置接受的类型
            instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
            instance.requestSerializer.timeoutInterval = 30;
            //            instance.responseSerializer = [AFHTTPResponseSerializer serializer];
//            instance.requestSerializer = [AFJSONRequestSerializer serializer];
//            [instance.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        }
    });
    
    if ([SISSUserAccount shared].access_token.length > 0) {
        
        [instance.requestSerializer setValue:[NSString stringWithFormat:@"%@ %@",[SISSUserAccount shared].token_type,[SISSUserAccount shared].access_token] forHTTPHeaderField:@"Authorization"];
        
    } else {
        [instance.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    return instance;
}

+ (instancetype)noUTF8Manager {
    static SISSNetworkingManager *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 实例化Manager
        instance = [[SISSNetworkingManager alloc]initWithBaseURL:[NSURL URLWithString:BASE_URL]];
        
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        instance.requestSerializer.timeoutInterval = 30;
        instance.requestSerializer = [AFJSONRequestSerializer serializer];
        [instance.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
    });
    if ([SISSUserAccount shared].access_token.length > 0) {
        [instance.requestSerializer setValue:[NSString stringWithFormat:@"%@ %@",[SISSUserAccount shared].token_type,[SISSUserAccount shared].access_token] forHTTPHeaderField:@"Authorization"];
    } else {
        [instance.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    return instance;
}

+ (instancetype)noBaseUrlManager {
    static SISSNetworkingManager *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 实例化Manager
        instance = [[SISSNetworkingManager alloc] init];
        
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        instance.requestSerializer.timeoutInterval = 12;
        instance.requestSerializer = [AFJSONRequestSerializer serializer];
        [instance.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
    });
    if ([SISSUserAccount shared].access_token.length > 0) {
        [instance.requestSerializer setValue:[NSString stringWithFormat:@"%@ %@",[SISSUserAccount shared].token_type,[SISSUserAccount shared].access_token] forHTTPHeaderField:@"Authorization"];
    } else {
        [instance.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    return instance;
}

- (AFJSONRequestSerializer *)JSONRequestSerializer{
    if(_JSONRequestSerializer == nil){
        _JSONRequestSerializer = [ AFJSONRequestSerializer serializer];
    }
    return _JSONRequestSerializer;
}

- (AFHTTPRequestSerializer *)HTTPRequestSerializer{
    if(_HTTPRequestSerializer == nil){
        _HTTPRequestSerializer = [AFHTTPRequestSerializer serializer];
    }
    return _HTTPRequestSerializer;
}

#pragma mark 重写
//- (instancetype)initWithBaseURL:(NSURL *)url {
//    
//    self = [super initWithBaseURL:url];
//    if (self) {
//        // 设置相应的缓存策略--URL应该加载源端数据，不使用本地缓存数据,忽略缓存直接从原始地址下载。
//        self.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
//        // 设置超时时间
//        //        self.requestSerializer.timeoutInterval = 3;
//        // 设置接受的类型
//        [self.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil]];
//    }
//    return self;
//}

- (void)GETWithURLString:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure {
//    if ([URLString containsString:@"jytbusiness"]) {
//        [kNetworkManager setValue:[NSURL URLWithString:BRANCH_BASE_URL] forKey:@"baseURL"];
//        [kNetworkNoUTF8Manager setValue:[NSURL URLWithString:BRANCH_BASE_URL] forKey:@"baseURL"];
//    } else {
//        [kNetworkManager setValue:[NSURL URLWithString:BASE_URL] forKey:@"baseURL"];
//        [kNetworkNoUTF8Manager setValue:[NSURL URLWithString:BASE_URL] forKey:@"baseURL"];
//    }
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * task, NSDictionary * responseObject) {
        // AFN的回调,默认就是在主线程
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

- (void)POSTWithURLString:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure {
//    if ([URLString containsString:@"jytbusiness"]) {
//        [kNetworkManager setValue:[NSURL URLWithString:BRANCH_BASE_URL] forKey:@"baseURL"];
//        [kNetworkNoUTF8Manager setValue:[NSURL URLWithString:BRANCH_BASE_URL] forKey:@"baseURL"];
//    } else {
//        [kNetworkManager setValue:[NSURL URLWithString:BASE_URL] forKey:@"baseURL"];
//        [kNetworkNoUTF8Manager setValue:[NSURL URLWithString:BASE_URL] forKey:@"baseURL"];
//    }
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    
    [self POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * task, NSDictionary * responseObject) {
        // AFN的回调,默认就是在主线程
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [SISSPublicSingleton shared].isHud = NO;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

- (void)PUTWithURLString:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    [self PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // AFN的回调,默认就是在主线程
        if (success) {
            success(responseObject);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

- (void)DELETEWithURLString:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    
    [self DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // AFN的回调,默认就是在主线程
        if (success) {
            success(responseObject);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

- (void)uploadFilesWithURLStr:(NSString *)URLStr serverName:(NSString *)serverName imagesArray:(NSArray *)imagesArray parameters:(NSDictionary *)parameters success:(void (^)(id))successBlock failed:(void (^)(NSError *))failedBlock {
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        if (![SISSPublicSingleton shared].isHud) {
            [MBProgressHUD YYR_ShowHUD:YES];
            [SISSPublicSingleton shared].isHud = YES;
        }
    }];
    [[SISSNetworkingManager sharedManager] POST:URLStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSUInteger i = 0 ;
        
        // 上传图片时，为了用户体验或是考虑到性能需要进行压缩
        for (UIImage *image in imagesArray) {
            
            // 压缩图片，指定宽度
//            UIImage *  resizedImage =  [UIImage imageCompressed:image withdefineWidth:width];
            NSData * imgData = UIImageJPEGRepresentation(image, 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmssSSS";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            // 拼接文件路径
            NSString *format = [PublicUtil yyr_contentTypeForImageData:imgData];
            NSString *fileName = [NSString stringWithFormat:@"%@%zd.%@",str,i,format != nil ? format : @""];
            // 拼接Data
            [formData appendPartWithFileData:imgData name:serverName fileName:fileName mimeType:@"application/octet-stream"];
            i++;
            //            [formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"picflie%ld",(long)i] fileName:@"image.png" mimeType:@" image/jpeg"];
            //            i--;
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"downLoadProcess = %@",uploadProgress);
//        if (uploadProgress) {
//
//            upLoadProgress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
//        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"responseObject = %@",responseObject);
        if (successBlock) {
            successBlock(responseObject);
        }
        [SISSPublicSingleton shared].isHud = YES;;
        [MBProgressHUD YYR_HideHUD:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error = %@",error);
        if (failedBlock) {
            
            failedBlock(error);
        }
        [SISSPublicSingleton shared].isHud = YES;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

- (void)uploadFilesWithURLStr:(NSString *)URLStr serverNames:(NSArray<NSString *> *)serverNames imagesArray:(NSArray<NSArray *> *)imagesArray parameters:(NSDictionary *)parameters success:(void (^)(id))successBlock failed:(void (^)(NSError *))failedBlock {
    
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    [[SISSNetworkingManager sharedManager] POST:URLStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSUInteger num = 0;
        // 上传图片时，为了用户体验或是考虑到性能需要进行压缩
        for (NSInteger i = 0; i < serverNames.count; i++) {
            for (UIImage *image in imagesArray[i]) {
                
                // 压缩图片，指定宽度
//                UIImage *  resizedImage =  [UIImage imageCompressed:image withdefineWidth:width];
                NSData *imgData = UIImageJPEGRepresentation(image, 0.5);
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmssSSS";
                NSString *str = [formatter stringFromDate:[NSDate date]];
                // 拼接文件路径
                NSString *format = [PublicUtil yyr_contentTypeForImageData:imgData];
                NSString *fileName = [NSString stringWithFormat:@"%@%zd.%@",str,num,format != nil ? format : @""];
                // 拼接Data
                [formData appendPartWithFileData:imgData name:serverNames[i] fileName:fileName mimeType:@"application/octet-stream"];
                num++;
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
        }
        [SISSPublicSingleton shared].isHud = YES;;
        [MBProgressHUD YYR_HideHUD:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failedBlock) {
            
            failedBlock(error);
        }
        [SISSPublicSingleton shared].isHud = YES;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

#pragma mark - GET 请求网络数据
/**
 *  请求网络数据
 *
 *  @param path             请求的地址
 *  @param paramters        请求的参数
 *  @param downLoadProgress 进度
 *  @param success          请求成功的回调
 *  @param failure          请求失败的回调
 */

- (void)GETDataWithPath:(NSString *)path
                 withParamters:(NSDictionary *)paramters
                  withProgress:(void(^) (float progress))downLoadProgress
                       success:(void(^) (BOOL isSuccess, id responseObject))success
                       failure:(void(^) (NSError *error))failure  {
    
    [[SISSNetworkingManager sharedManager] GET:path parameters:paramters progress:^(NSProgress * _Nonnull downloadProgress) {
        
        //        NSLog(@"downLoadProcess = %@",downLoadProgress);
        if (downloadProgress) {
            
            downLoadProgress(downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        }
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        NSLog(@"responseObject = %@",responseObject);
        if (success) {
            
            success(YES,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //        NSLog(@"error = %@",error);
        if (failure) {
            
            failure(error);
        }
    }];
    
}

#pragma mark - POST 传送网络数据
/**
 *  传送网络数据
 *
 *  @param path           请求的地址
 *  @param paramters      请求的参数
 *  @param upLoadProgress 进度
 *  @param success        请求成功的回调
 *  @param failure        请求失败的回调
 */
- (void)POSTDataWithPath:(NSString *)path
               withParamters:(NSDictionary *)paramters
                withProgress:(void(^) (float progress))upLoadProgress
                     success:(void(^) (BOOL isSuccess, id responseObject))success
                     failure:(void(^) (NSError *error))failure {
    
    [[SISSNetworkingManager sharedManager] POST:path parameters:paramters progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //        NSLog(@"downLoadProcess = %@",uploadProgress);
        if (uploadProgress) {
            
            upLoadProgress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        NSLog(@"responseObject = %@",responseObject);
        if (success) {
            
            success(YES,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //        NSLog(@"error = %@",error);
        if (failure) {
            
            failure(error);
        }
    }];
}

#pragma mark POST 上传图片
/**
 *  上传图片
 *
 *  @param path           上传的地址---需要填写完整的url
 *  @param paramters      上传图片预留参数---视具体情况而定，可移除
 *  @param imageArray     上传的图片数组
 *  @param width          图片要被压缩到的宽度
 *  @param upLoadProgress 进度
 *  @param success        请求成功的回调
 *  @param failure        请求失败的回调
 */
- (void)POSTImageWithPath:(NSString *)path
                withParamters:(NSDictionary *)paramters
               withImageArray:(NSArray *)imageArray
              withtargetWidth:(CGFloat )width
                 withProgress:(void(^) (float progress))upLoadProgress
                      success:(void(^) (BOOL isSuccess, id responseObject))success
                      failure:(void(^) (NSError *error))failure {
    
    [[SISSNetworkingManager sharedManager] POST:path parameters:paramters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSUInteger i = 0 ;
        
        // 上传图片时，为了用户体验或是考虑到性能需要进行压缩
        for (UIImage * image in imageArray) {
            
            // 压缩图片，指定宽度
            UIImage *  resizedImage =  [UIImage imageCompressed:image withdefineWidth:width];
            NSData * imgData = UIImageJPEGRepresentation(resizedImage, 0.5);
            // 拼接Data
            [formData appendPartWithFileData:imgData name:@"pic" fileName:@"image.png" mimeType:@"application/octet-stream"];
            i--;
            //            [formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"picflie%ld",(long)i] fileName:@"image.png" mimeType:@" image/jpeg"];
            //            i--;
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"downLoadProcess = %@",uploadProgress);
        if (uploadProgress) {
            
            upLoadProgress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"responseObject = %@",responseObject);
        if (success) {
            
            success(YES,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error = %@",error);
        if (failure) {
            
            failure(error);
        }
    }];
}

#pragma mark POST 上传视频
/**
 *  上传视频
 *
 *  @param path           上传的地址--需要填写完整的url
 *  @param videoPath      上传的视频--本地沙盒的路径
 *  @param paramters      上传视频预留参数--根据具体需求而定，可以出
 *  @param upLoadProgress 进度
 *  @param success        请求成功的回调
 *  @param failure        请求失败的回调
 */
- (void)POSTImageWithPath:(NSString *)path
                withVideoPath:(NSString *)videoPath
                withParamters:(NSDictionary *)paramters
                 withProgress:(void(^) (float progress))upLoadProgress
                      success:(void(^) (BOOL isSuccess, id responseObject))success
                      failure:(void(^) (NSError *error))failure {
    
    // 获取视频资源
    AVURLAsset * avUrlAsset = [AVURLAsset assetWithURL:[NSURL URLWithString:videoPath]];
    // 视频压缩
    //    NSString *const AVAssetExportPreset640x480;
    //    NSString *const AVAssetExportPreset960x540;
    //    NSString *const AVAssetExportPreset1280x720;
    //    NSString *const AVAssetExportPreset1920x1080;
    //    NSString *const AVAssetExportPreset3840x2160;
    
    AVAssetExportSession  *  avAssetExport = [[AVAssetExportSession alloc] initWithAsset:avUrlAsset presetName:AVAssetExportPreset640x480];
    // 获取上传的时间
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    // 转化后直接写入Library---caches
    NSString *  videoWritePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:[NSString stringWithFormat:@"/output-%@.mp4",[formatter stringFromDate:[NSDate date]]]];
    avAssetExport.outputURL = [NSURL URLWithString:videoWritePath];
    avAssetExport.outputFileType =  AVFileTypeMPEG4;
    [avAssetExport exportAsynchronouslyWithCompletionHandler:^{
        
        switch ([avAssetExport status]) {
                
            case AVAssetExportSessionStatusCompleted:
            {
                
                [[SISSNetworkingManager sharedManager] POST:path parameters:paramters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                    
                    //获得沙盒中的视频内容
                    
                    [formData appendPartWithFileURL:[NSURL fileURLWithPath:videoWritePath] name:@"write you want to writre" fileName:videoWritePath mimeType:@"video/mpeg4" error:nil];
                    
                } progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                    NSLog(@"downLoadProcess = %@",uploadProgress);
                    if (uploadProgress) {
                        
                        upLoadProgress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
                    }
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
                    
                    NSLog(@"responseObject = %@",responseObject);
                    if (success) {
                        
                        success(YES,responseObject);
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    NSLog(@"responseObject = %@",error);
                    if (failure) {
                        
                        failure(error);
                    }
                }];
                
                break;
            }
            default:
                break;
        }
    }];
}

#pragma mark DOWNLOAD 文件下载
- (void)DownLoadDataWithPath:(NSString *)path
                      withParamters:(NSDictionary *)paramters
                       withSavaPath:(NSString *)savePath
                       withProgress:(void(^) (float progress))downLoadProgress
                            success:(void(^) (BOOL isSuccess, id responseObject))success
                            failure:(void(^) (NSError *error))failure {
    
    [[SISSNetworkingManager sharedManager] downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]] progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"downLoadProcess = %@",downLoadProgress);
        if (downloadProgress) {
            
            downLoadProgress(downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        return  [NSURL URLWithString:savePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (error) {
            
            failure(error);
        }
        
    }];
}

#pragma mark - DELETE 删除资源
- (void)DELETEDataWithPath:(NSString *)path
                    withParamters:(NSDictionary *)paramters
                          success:(void (^) (BOOL isSuccess, id responseObject))success
                          failure:(void (^) (NSError *error))failure {
    
    [[SISSNetworkingManager  sharedManager] DELETE:path parameters:paramters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"success %@",success);
        if (success) {
            
            success(YES,success);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"failure %@",error);
        if (failure) {
            
            failure(error);
        }
    }];
    
}

#pragma mark - PUT 更新全部属性
- (void)PUTDataWithPath:(NSString *)path
              withParamters:(NSDictionary *)paramters
                    success:(void(^) (BOOL isSuccess, id responseObject))success
                    failure:(void(^) (NSError *error))failure {
    
    [[SISSNetworkingManager sharedManager] PUT:path parameters:paramters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"success %@",success);
        if (success) {
            
            success(YES,success);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"failure %@",error);
        if (failure) {
            
            failure(error);
        }
    }];
}

#pragma  mark - PATCH 改变资源状态或更新部分属性
- (void)PATCHDataWithPath:(NSString *)path
                withParamters:(NSDictionary *)paramters
                      success:(void (^) (BOOL isSuccess, id responseObject))success
                      failure:(void (^) (NSError *error))failure {
    [[SISSNetworkingManager sharedManager] PATCH:path parameters:paramters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"success %@",success);
        if (success) {
            
            success(YES,success);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"failure %@",error);
        if (failure) {
            
            failure(error);
        }
    }];
}

#pragma mark - 取消网络请求--全部请求
- (void)cancelAllNetworkRequest {
    
    [[SISSNetworkingManager sharedManager].operationQueue cancelAllOperations];
}

#pragma mark - 取消网络请求--指定请求
/**
 *  取消指定的url请求
 *
 *  @param type 该请求的请求类型
 *  @param path 该请求的完整url
 */
-(void)cancelHttpRequestWithType:(NSString *)type WithPath:(NSString *)path {
    
    NSError * error;
    // 根据请求的类型 以及 请求的url创建一个NSMutableURLRequest---通过该url去匹配请求队列中是否有该url,如果有的话 那么就取消该请求
    NSString * urlToPeCanced = [[[[SISSNetworkingManager sharedManager].requestSerializer requestWithMethod:type URLString:path parameters:nil error:&error] URL] path];
    
    for (NSOperation * operation in [SISSNetworkingManager sharedManager].operationQueue.operations) {
        
        // 如果是请求队列
        if ([operation isKindOfClass:[NSURLSessionTask class]]) {
            
            // 请求的类型匹配
            BOOL hasMatchRequestType = [type isEqualToString:[[(NSURLSessionTask *)operation currentRequest] HTTPMethod]];
            
            // 请求的url匹配
            
            BOOL hasMatchRequestUrlString = [urlToPeCanced isEqualToString:[[[(NSURLSessionTask *)operation currentRequest] URL] path]];
            
            // 两项都匹配的话  取消该请求
            if (hasMatchRequestType&&hasMatchRequestUrlString) {
                
                [operation cancel];
            }
        }
    }
}


/**
 存储图片获取图片路径
 
 @param images 图片
 @return 路径数组
 */
- (NSArray *)getImageFilePathWithImages:(NSArray *)images {
    
    //    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:images.count];
    //    for (UIImage *image in images) {
    //        [arrM addObject:[UIImage imageWithData:[self resetSizeOfImageData:image maxSize:1]]];
    //    }
    //    images = arrM.copy;
    
    // 拼接缓存目录
    NSString *uploadloadDir = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Upload"];
    // 打开文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 创建Upload目录
    if (![fileManager fileExistsAtPath:uploadloadDir]) {
        [fileManager createDirectoryAtPath:uploadloadDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:images.count];
    for (NSInteger i = 0; i < images.count; i++) {
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmssSSS";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        // 拼接文件路径
        NSString *filePath = [uploadloadDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%zd",str,i]];
        [UIImageJPEGRepresentation(images[i], 1) writeToFile:filePath atomically:YES];
        [arr addObject:filePath];
    }
    
    return arr.copy;
}

@end
